import Node from './Node'

class Img extends Node {
	constructor(src) {
		super()
		const originImage = new Image()
		const ob = {
			tag: {
				value: 'img',
				configurable: false,
				writable: false,
				enumerable: false
			},
			originImage: {
				value: originImage,
				configurable: false,
				writable: false,
				enumerable: false
			},
			loaded: {
				value: false,
				configurable: false,
				writable: true,
				enumerable: false
			},
			src: {
				set(val) {
					if (val && val != src) {
						src = val
						this.originImage.src = val
						this.loaded = false
					}
				},
				get() {
					return src || ''
				}
			}
		}
		Object.defineProperties(this, ob)
		originImage.crossorigin = 'anonymous'
		originImage.onload = () => {
			this.loaded = true
		}
		this.originImage.src = src
	}
	render(ctx) {
		if (!ctx) return
		const props = this.props,
			hw = props.width / 2,
			hh = props.height / 2,
			cx = props.x + this._x + hw,
			cy = props.y + this._y + hh
		ctx.save()
		ctx.translate(cx, cy)
		//opacity
		ctx.globalAlpah = props.opacity
		//rotate
		ctx.rotate(props.rotate)
		//scale
		ctx.scale(props.scale[0], props.scale[1])
		//阴影
		if (props.shadow.length === 4) {
			ctx.shadowColor = props.shadow[0]
			ctx.shadowOffsetX = props.shadow[1]
			ctx.shadowOffsetY = props.shadow[2]
			ctx.shadowBlur = props.shadow[3]
		}
		//边框
		if (props.border[0] > 0 && props.border[1]) {
			ctx.lineWidth = props.border[0]
			ctx.strokeStyle = props.border[1]
			ctx.stroke()
		}
		if (this.loaded) ctx.drawImage(this.originImage, -hw, -hh, props.width, props.height)
		ctx.restore()
	}
}

export default Img